using System.Collections;
using System.Reflection;
using System.Web.Mvc;
using EmbeddedReport.Web.Models;
using Microsoft.Reporting.WebForms;

namespace EmbeddedReport.Web.Controllers
{
    public class ReportsController : Controller
    {
        //
        // GET: /Reports/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ReportPdf()
        {
            var ReportPath = Server.MapPath("~/Report1.rdlc");

            object Model = new NiceDataList();

            RenderReport(ReportPath, "PDF", Model);

            return View();
        }

        public ActionResult ReportExcel()
        {
            var ReportPath = Server.MapPath("~/Report1.rdlc");

            object Model = new NiceDataList();

            RenderReport(ReportPath, "Excel", Model);

            return View();
        }

        private void RenderReport(string ReportPath, string reportType, object Model)
        {
            var localReport = new LocalReport { ReportPath = ReportPath };

            //Give the collection a name (EmployeeCollection) so that we can reference it in our report designer
            var reportDataSource = new ReportDataSource("NiceData", Model);
            localReport.DataSources.Add(reportDataSource);

            string mimeType;
            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            var deviceInfo =
                string.Format(
                    "<DeviceInfo><OutputFormat>{0}</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight><MarginTop>0.5in</MarginTop><MarginLeft>1in</MarginLeft><MarginRight>1in</MarginRight><MarginBottom>0.5in</MarginBottom></DeviceInfo>",
                    reportType);

            Warning[] warnings;
            string[] streams;

            //Render the report
            var renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            //Clear the response stream and write the bytes to the outputstream
            //Set content-disposition to "attachment" so that user is prompted to take an action
            //on the file (open or save)
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }
    }
}